package com.hurl.waguji.biz.download;

import java.io.File;
import java.util.Date;

import org.hibernate.ScrollableResults;
import org.hibernate.criterion.Restrictions;
import org.testng.log4testng.Logger;

import com.hurl.library.http.HttpRequest;
import com.hurl.library.util.DateUtils;
import com.hurl.waguji.base.Configuration;
import com.hurl.waguji.base.DateService;
import com.hurl.waguji.base.dao.HibernateDao;
import com.hurl.waguji.base.dao.HibernateService;
import com.hurl.waguji.base.dataprocess.ProcessHelper;
import com.hurl.waguji.base.dataprocess.ProcessResult;
import com.hurl.waguji.base.dataprocess.ProcessException;
import com.hurl.waguji.base.dataprocess.ProcessParams;
import com.hurl.waguji.persistence.DmGpBO;
import com.hurl.waguji.persistence.JcsjCjmxFileTencentBO;
import com.hurl.waguji.persistence.JcsjCjmxFileTencentBOId;

public class MrhqCjmxFileTencentIdentifier extends DownloadIdentifier {
	private static final Logger log = Logger.getLogger(MrhqCjmxFileTencentIdentifier.class);
	private HttpRequest requester = new HttpRequest();
	
	public MrhqCjmxFileTencentIdentifier() {
		super("jcsj.mrhq.cjmx.file.tencent", "【下载】每日成交明细文件（腾讯网）");
	}

	@Override
	public BaseDownloadProcessor newProcessor(ProcessParams params) {
		throw new UnsupportedOperationException("不需要使用这个方法不支持该操作！");
	}

	private void prepareDownload(HibernateDao dao,Date lastTradingDate,  File rootLocation){
		dao.queryByHQL("delete from "+JcsjCjmxFileTencentBO.class.getSimpleName()+" where id.rq=:rq").setDate("rq", lastTradingDate).executeUpdate();
		if(!rootLocation.exists()){
			rootLocation.mkdirs();
		}
		
	}
	public synchronized ProcessResult execute(ProcessParams params)throws ProcessException{

		Date lastTradingTime = DateService.getLastTradingTimeFromWeb();
		Date lastTradingDate = DateUtils.getDate(lastTradingTime);
		
		/* 只能在交易当天下载  */
		if(!DateService.isNowAfterTradingTime(lastTradingTime,1)){
			throw new ProcessException("请在交易日下午4点以后下载！");
		}

		HibernateDao dao = HibernateService.getDao();
		
		/* 不能重复下载 */
		if(ProcessHelper.isAlreadyProcessed(this.getId(), lastTradingDate, dao)){
			throw new ProcessException(DateUtils.formatDate(lastTradingDate, DateUtils.FORMAT_DATE_CN)+"的数据已经下载过！");
		}

		/* 开始下载，做一些清理工作 */
		File rootLocation = new File(Configuration.getTencentCjmxFileLocation(),DateUtils.formatDate(lastTradingDate, "yyyy_MM_dd"));
		prepareDownload(dao,lastTradingDate,rootLocation);
		
		String rqStr = DateUtils.formatDate(lastTradingDate, "yyyyMMdd");
		ScrollableResults results = dao.createCriteria(DmGpBO.class).add(Restrictions.eq("flag", 'Y')).setReadOnly(true).scroll();
		String url = null;
		String fileName = null;
		String filePath = null;
		File fileLocation = null;
		Date startTime = DateService.getCurrentTimeFromServer();
		int count=0;
		try{
			while(results.next()){
				DmGpBO bo = (DmGpBO)results.get(0);
				
				/* 下载文件 */
				url = "http://stock.gtimg.cn/data/index.php?appn=detail&action=download&c="+bo.getGpDm().toLowerCase()+"&d="+rqStr;
				fileLocation = new File(rootLocation,bo.getGpDm()+"_"+rqStr+".xls");
				if(!fileLocation.exists()){
					log.debug("保存成交明细文件："+fileLocation);
					requester.requestFile(url,fileLocation);
				}
				
				/* 保存下载信息 */
				fileName = fileLocation.getName();
				filePath = fileLocation.getAbsolutePath();
				dao.save(new JcsjCjmxFileTencentBO(new JcsjCjmxFileTencentBOId(bo.getGpDm(), lastTradingDate), fileName, filePath, startTime));
				
				count++;
				if(count%20==0){
					dao.flush();
					dao.clear();
				}
			}
		}catch(Throwable t){
			/* 保存失败的下载结果 */
			ProcessResult result = new ProcessResult(this);
			result.setCount(count);
			result.setRq(lastTradingDate);
			result.setStartTime(startTime);
			result.setEndTime(DateService.getCurrentTimeFromServer());
			result.setSuccess(false);
			result.setError(t);
			ProcessHelper.saveProcessResult(result,dao);
			dao.flush();
			dao.clear();
			return result;
		}
		
		/* 保存成功下载结果 */
		ProcessResult result = new ProcessResult(this);
		result.setCount(count);
		result.setRq(lastTradingDate);
		result.setStartTime(startTime);
		result.setEndTime(DateService.getCurrentTimeFromServer());
		result.setSuccess(true);
		ProcessHelper.saveProcessResult(result,dao);
		dao.flush();
		dao.clear();
		return result;
	}
}
